package org.deri.socializer.activities.chat;

import java.util.Iterator;


import org.deri.socializer.SocializerApplication;
import org.deri.socializer.activities.start.StartActivity;
import org.deri.socializer.com.xmpp.XmppClient;
import org.deri.socializer.com.xmpp.XmppPrivateChat;
import org.deri.socializer.util.XMPPUtilities;
import org.deri.vor.R;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class ChatListActivity extends Activity {

	boolean created = false;
	SocializerApplication app;
	XmppClient xmppClient;
	

	
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.chatlistview);

	    this.app = ((SocializerApplication)getApplicationContext());
        this.xmppClient = this.app.getXMPPClient();

		this.addOpenGroupChats();
        this.addOpenPrivateChats();
		
        share_button();
        
    	this.created = true;
    }
	
	private void back() {
    	Intent intent = new Intent(getApplicationContext(), StartActivity.class);
    	startActivity(intent);
    	finish();
    }
	
	private void addOpenGroupChats() {
		try {
			System.out.println("[ChatListActivity] #groupchats = " + this.xmppClient.getGroupChats().size());
			TableLayout table = (TableLayout)findViewById(R.id.tableLayoutGroupChats);
			table.removeAllViews();
			
			Iterator<String> groupChatIter = this.xmppClient.getGroupChats().keySet().iterator();
			String currentGroupChat;
			boolean hasOpenGroupChats = false;
			while (groupChatIter.hasNext()) {
				hasOpenGroupChats = true;
				currentGroupChat = groupChatIter.next();

				if (currentGroupChat == null)
					System.out.println("[ChatListActivity.addOpenGroupChats] currentGroupChat == null");
				
				System.out.println(currentGroupChat);
				if (!currentGroupChat.endsWith(SocializerApplication.XMPP_GROUP_CHAT_SUFFIX_WEB))
					return;
	
				
				String room = currentGroupChat.substring(0, (currentGroupChat.length() - SocializerApplication.XMPP_GROUP_CHAT_SUFFIX_WEB.length()));
				System.out.println(currentGroupChat);
				/* Create a new row to be added. */
		        TableRow tr = new TableRow(this);
		        /* Create a Button to be the row-content. */
		        
		        final TextView text = new TextView(this);
		        text.setText(room);
		        text.setTextColor(Color.rgb(0, 0, 0));
		        
		        Button buttonEnter = new Button(this);
		        buttonEnter.setText("Enter");
		        buttonEnter.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						openGroupChat(text.getText().toString());
					}
				});
		        
	
		        Button buttonLeave = new Button(this);
		        buttonLeave.setText("Close");
		        buttonLeave.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						closeGroupChat(text.getText().toString());
					}
				});
		                    
		        /* Add Button to row. */
		        tr.addView(text);
		        tr.addView(buttonLeave);
		        tr.addView(buttonEnter);
		        
		        /* Add row to TableLayout. */
		        table.addView(tr,new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
			}
	
			if (!hasOpenGroupChats) {
				 TableRow tr = new TableRow(this);
			     tr.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
	
			     final TextView text = new TextView(this);
			     text.setTextColor(Color.rgb(0, 0, 0));
			     text.setText("(No open group chats)");
			    
			     tr.addView(text);
			     table.addView(tr,new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
			}
		} catch (Exception exc) {
			exc.printStackTrace();
		}
	}
	
	
	
	private void addOpenPrivateChats() {
		System.out.println("[ChatListActivity] #private chats = " + this.xmppClient.getPrivateChats().size());
		TableLayout table = (TableLayout)findViewById(R.id.tableLayoutPrivateChats);
		table.removeAllViews();
		Iterator<String> chatIter = this.xmppClient.getPrivateChats().keySet().iterator();
		String currentChat;
		boolean hasOpenPrivateChats = false;
		while (chatIter.hasNext()) {
			hasOpenPrivateChats = true;
			currentChat = chatIter.next();

			System.out.println("[ChatListActivity.addOpenPrivateChats] chat jid: " + currentChat);
			/* Create a new row to be added. */
	        TableRow tr = new TableRow(this);
	        tr.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
	        /* Create a Button to be the row-content. */
	        
	        final TextView text = new TextView(this);
	        //text.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
	        text.setText(XMPPUtilities.getSenderName(currentChat));
	        text.setTextColor(Color.rgb(0, 0, 0));

	        final String userJid = currentChat;

	        
	        Button buttonEnter = new Button(this);
	        buttonEnter.setText("Enter");
	        buttonEnter.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					openPrivateChat(userJid);
				}
			});
	        

	        Button buttonLeave = new Button(this);
	        buttonLeave.setText("Close");
	        buttonLeave.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					closePrivateChat(userJid);
				}
			});
	                    
	        /* Add Button to row. */
	        tr.addView(text);
	        tr.addView(buttonLeave);
	        tr.addView(buttonEnter);
	        
	        /* Add row to TableLayout. */
	        table.addView(tr,new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
		}

		if (!hasOpenPrivateChats) {
	        TableRow tr = new TableRow(this);
	        tr.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

	        final TextView text = new TextView(this);
	        text.setTextColor(Color.rgb(0, 0, 0));
	        text.setText("(No open private chats)");

	        tr.addView(text);
	        table.addView(tr,new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));	
		}
	}
	
	
	
	private void openGroupChat(String room) {
		this.app.setCurrentDomainWeb(room);
    	this.xmppClient.joinWebGroupChat(room);
    	this.xmppClient.setLastXmppWebChat(this.xmppClient.getXmppWebGroupChat(room));
    	Intent intent = new Intent(this.app.getApplicationContext(), ChatActivity.class);
    	this.startActivity(intent);
	}
	
	private void closeGroupChat(String room) {
    	this.xmppClient.leaveWebGroupChat(room);
    	this.addOpenGroupChats();
	}
	
	private void openPrivateChat(String userJid) {
		XmppPrivateChat privateChat = this.xmppClient.getXmppPrivateChat(userJid, false);
		if (privateChat != null) {
			this.xmppClient.setLastXmppWebChat(privateChat);
			Intent intent = new Intent(this.app.getApplicationContext(), ChatActivity.class);
			this.startActivity(intent);
		}
	}
	
	private void closePrivateChat(String userJid) {
    	this.xmppClient.closePrivateChat(userJid);
    	this.addOpenPrivateChats();
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
	    if (!created) {
	    	Intent intent = getIntent();
	    	finish();
	    	startActivity(intent);

	    }
		super.onResume();
		SocializerApplication.runningActivities++;
	}


	@Override
	protected void onPause() {
	    super.onPause();
	    created = false;
	    SocializerApplication.runningActivities--;
	}

	@Override
	protected void onDestroy() {
	    super.onDestroy();
	    this.app.checkActivityState();
	}
	
	
		private void share_button(){
			Button button = (Button) findViewById(R.id.btnBack);
			button.setOnClickListener(ms_layout);

			// About Button OnClick
			button = (Button) findViewById(R.id.btnAbout);
			button.setOnClickListener(ms_layout);

			// Home Button OnClick
			button = (Button) findViewById(R.id.btnHome);
			button.setOnClickListener(ms_layout);
			
			ImageView im  = (ImageView) findViewById(R.id.vor_icon);
			im.setClickable(true);
			im.setOnClickListener(ms_layout);

			im = (ImageView) findViewById(R.id.nuig_icon);
			im.setClickable(true);
			im.setOnClickListener(ms_layout);

			im = (ImageView) findViewById(R.id.deri_icon);
			im.setClickable(true);
			im.setOnClickListener(ms_layout);
		}
	    
	    
	    private OnClickListener ms_layout	=	new OnClickListener(){

			@Override
			public void onClick(View v) {
				switch (v.getId()){
				case R.id.btnAbout  : { jump(72); break;}
				case R.id.btnHome 	: { jump(2); break;}
				case R.id.btnBack  	: { back(); break;}
				case R.id.vor_icon  : { jump(3); break;}
				case R.id.deri_icon : { jump(19); break;}
				case R.id.nuig_icon : { jump(40); break;}
				}
			}
	    };
	    
	    
	    private void jump(int page){
	    	Intent i = new Intent();
	    	i.putExtra("cl",page);
	    	i.setClassName("org.deri.vor", "org.deri.vor.VovolOceanRaceActivity");
			startActivity(i);
			finish();
	    }
}
